// Copyright (c) Microsoft Corporation. All rights reserved.

namespace SPPivotViewer.HttpHandler.Internal
{
    using System;
    using System.Drawing;
    using System.IO;
    using System.Net;
    using System.Drawing.Imaging;
    using System.Web;
    using System.Collections.Generic;
    using SPPivotViewer.Utility;
    using Microsoft.SharePoint;


    /// <summary>
    /// Create an item image by loading it from a URL.
    /// </summary>
    internal class WebImage : ImageBase
    {
        // Constructors, Finalizer and Dispose
        //======================================================================

        public WebImage(Uri url, string title, Dictionary<string, string> metadata)
        {
            m_url = url;
            m_metadata = metadata;
            m_title = title;
        }


        // Protected Methods
        //======================================================================

        protected override Image[] MakeImage()
        {
            using (WebClient web = new WebClient())
            {
                web.UseDefaultCredentials = true;
                List<Image> imgReturn=new List<Image>();
                try
                {
                    using (Stream webStream = web.OpenRead(m_url))
                    {
                        using (Image img = Image.FromStream(webStream))
                        {
                            FillLayers(img, m_title, m_metadata, ref imgReturn);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.ErrorMessage("Web Image", ex.ToString());

                    string strImgSub=PV4SPSettings.GetValue(SPContext.Current.Web, PV4SPSettings.cstImgSub);
                    if (strImgSub != string.Empty)
                    {
                        using (Stream webStream = web.OpenRead(strImgSub))
                        {
                            using (Image img = Image.FromStream(webStream))
                            {
                                FillLayers(img, m_title, m_metadata, ref imgReturn);
                            }
                        }

                    }
                    else
                    {
                        using (Image img = Image.FromStream(this.GetType().Assembly.GetManifestResourceStream("SPPivotViewer.Resources.pv4sp256.png")))
                        {
                            FillLayers(img, m_title, m_metadata, ref imgReturn);
                        }
                    }
                    
                }
                return imgReturn.ToArray() ;

            }
        }



        // Private Fields
        //======================================================================

        Uri m_url;
        string m_title;
        Dictionary<string, string> m_metadata;
    }

}
